#pragma once

#include "Socket.h"
#include "Channel.h"
#include "EventLoop.h"
#include "Buffer.h"
#include "Timestamp.h"

#include <memory>
#include <atomic>

class Connection;
using ConnectionPtr = std::shared_ptr<Connection>;

//std::enable_shared_from_this模板类，用于返回shared_ptr类型的this指针
class Connection:public std::enable_shared_from_this<Connection>
{
private:
    
    EventLoop* m_loop;
    std::unique_ptr<Socket> m_clientsock;
    std::unique_ptr<Channel> m_clientchannel;

    Buffer m_inputbuffer;
    Buffer m_outputbuffer;
    std::atomic_bool m_disconnect;
    
    std::function<void(ConnectionPtr)> m_close_callback;
    std::function<void(ConnectionPtr)> m_error_callback;
    std::function<void(ConnectionPtr,std::string&)> m_on_message_callback;
    std::function<void(ConnectionPtr)> m_send_complete_callback;

    Timestamp m_lasttime;
public:
    Connection(EventLoop* loop,std::unique_ptr<Socket> clientsock);
    ~Connection();

    std::string ip();
    uint16_t port();
    int fd();

    void on_message();
    void close_callback();
    void error_callback();
    void write_callback();

    void set_close_callback(std::function<void(ConnectionPtr)> fn);
    void set_error_callback(std::function<void(ConnectionPtr)> fn);
    void set_on_message_callback(std::function<void(ConnectionPtr,std::string&)> fn);
    void set_send_complete_callback(std::function<void(ConnectionPtr)> fn);

    void send(const char* data,size_t size);
    void send_in_loop(const char* data,size_t size);
    void send_string_in_loop(std::string data);

    bool is_timeout(time_t now,time_t threshold);

    void clientchannel_enableread();

    void send_directly();
};